import router from "@/router";
// 链接axios
import axios from "axios";
// 链接qs
import qs from "qs";
// 链接vant2
import { Dialog } from "vant";

const instance = axios.create({
  // 头部地址
  baseURL: "http://47.93.101.203",
  // 请求超时
  timeout: 10000,
});
instance.interceptors.request.use(
  function (config) {
    // 拼接token
    if (localStorage.getItem("token")) {
      config.headers["Authori-zation"] = `Bearer ${localStorage.getItem(
        "token"
      )}`;
    }
    // qs转换
    config.data =
      config.data instanceof FormData ? config.data : qs.stringify(config.data);
    return config;
  },
  function (error) {
    // 对请求错误做些什么
    return Promise.reject(error);
  }
);
instance.interceptors.response.use(
  function (response) {
    // 判断状态码
    if (response.status == 200) {
      // 状态码登录410000退出登录
      if (response.status == 410000) {
        localStorage.removeItem("token");
        router.replace({
          path: "login",
          query: { redirect: router.currentRoute.fullPath },
        });
      }
    }
    return response;
  },
  function (error) {
    // 判断网络请求
    if (error.message == "Network Error") {
      // 弹出弹窗显示没有网络
      Dialog.confirm(
        // 弹出窗
        { message: "网络错误，请检查服务端，请【点击重试】！", title: "提示" },
        {
          // 点击重新获取检测是否有网络
          confirmButtonText: "点击重试",
          type: "warning",
          showClose: false,
          showCancelButton: false,
          closeOnClickModal: false,
        }
      ).then(() => {
        tautology(error);
      });
    }
    // 返回错误
    return Promise.reject(error);
  }
);

//再次发起请求
function tautology(err) {
  // 创建一个新的Promise;
  let back = new Promise(function (resolve) {
    resolve();
  });
  // 返回重复请求
  return back.then(function () {
    return instance(err.config);
  });
}
// 抛出
export default instance;
